package com.echatim.controller;

import com.broker.base.protocol.response.Resp;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ConditionalOnProperty(name="echatim.sdk.auth-type", havingValue="community")
@ControllerAdvice
public class CustomResponseBodyAdvice implements ResponseBodyAdvice {


    @Override
    public Object beforeBodyWrite(Object returnValue, MethodParameter methodParameter,
                                  MediaType mediaType, Class clz, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        if(returnValue instanceof Resp){
            long code = ((Resp) returnValue).getCode();
            if(code != 0){
                // 使用451码表示业务出现错误.
                serverHttpResponse.setStatusCode(HttpStatus.UNAVAILABLE_FOR_LEGAL_REASONS);
            }
        }
        return returnValue;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class clas) {
        return true;
    }
}
